"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试
Case Name   : 闰年时创建多个schema，并创建同名对象
Create At   : 2021/01/27
@zou_jialiang0505328126
Description :
    1.设置操作系统时间为2020-02-28 23:58:00
    2.创建10个schema
    3.每个schema中都创建表，并插入数据
    4.查询数据
    5.修改schema
    6.删除schema
Expect      :
    1.设置成功
    2.创建成功
    3.创建表并插入数据成功
    4.查询结果正确
    5.修改成功
    6.删除成功
History     :
    Modified by @wan005 2021/3/23: 增加环境时区修复步骤
"""

import unittest
from yat.test import Node
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class Ddldatabase(unittest.TestCase):
    commonshpri = CommonSH('PrimaryDbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('----Opengauss_Reliability_Dbsys_Case239.py 开始执行------')
        self.db_primary_db_user = Node(node='PrimaryDbUser')
        self.db_primary_root_node = Node(node='PrimaryRoot')
        self.db_standby1_root_node = Node(node='Standby1Root')
        self.constant = Constant()
        self.common = Common('PrimaryRoot')
        self.schema_name = ['schema_test1', 'schema_test2', 'schema_test3',
                            'schema_test4', 'schema_test5', 'schema_test6',
                            'schema_test7', 'schema_test8', 'schema_test9',
                            'schema_test10']

        result = self.common.check_system_timezone(
            *('PrimaryRoot', 'Standby1Root', 'Standby2Root'))
        self.log.info(result)
        self.assertTrue(result)

        self.log.info('=====安装ntp服务=======')
        result = self.db_primary_root_node.sh('yum install -y ntp').result()
        self.log.info(result)
        result = self.db_primary_root_node.sh(
            'systemctl enable ntpd').result()
        self.log.info(result)
        result = self.db_primary_root_node.sh('systemctl start ntpd').result()
        self.log.info(result)

    def test_basebackup(self):
        self.log.info("-------1.设置操作系统时间为02/28/2020 23:59:00------------")
        datecmd = "date -s '02/28/2020 23:59:00';hwclock --systohc;" \
                  "service ntpd stop;ntpdate ntp.api.bz;service ntpd start"
        self.log.info(datecmd)
        result = self.db_primary_root_node.sh(datecmd).result()
        self.log.info(result)

        result = self.db_primary_root_node.sh('date').result()
        self.log.info(result)
        before_time = self.commonshpri.executDbSql('select now();')
        self.log.info(before_time)
        self.assertIn("2020-02-28", before_time)

        self.log.info('-------------------2.创建10个schema-----------------')
        for schname in self.schema_name:
            sql = f"drop schema if exists {schname};create schema {schname};"
            result = self.commonshpri.executDbSql(sql)
            self.log.info(result)
            self.assertIn(self.constant.create_schema_success_msg, result)

        self.log.info('---------------3.每个schema中都创建表，并插入数据--------------')
        value = 0
        for schname in self.schema_name:
            sql = f"create table {schname}.{schname}_tbl(i int);" \
                f"create index {schname}.{schname}_idx " \
                f"on {schname}.{schname}_tbl(i);" \
                f"declare num number := 1; " \
                f"begin " \
                f"for num in 1 .. 20000 loop " \
                f"insert into {schname}.{schname}_tbl values({value}); " \
                f"end loop; end;"
            value += 1
            result = self.commonshpri.executDbSql(sql)
            self.log.info(result)
            self.assertIn(self.constant.TABLE_CREATE_SUCCESS, result)
            self.assertIn(self.constant.CREATE_INDEX_SUCCESS_MSG, result)
            self.assertIn('ANONYMOUS BLOCK EXECUTE', result)

        self.log.info('-----------------------4.查询数据------------------')
        value = 0
        for schname in self.schema_name:
            sql = f"select count(*) from {schname}.{schname}_tbl " \
                f"where i = {value};"
            value += 1
            result = self.commonshpri.executDbSql(sql)
            self.log.info(result)
            self.assertIn('20000', result)

        self.log.info('-----------------------5.修改schema------------------')
        value = 0
        for schname in self.schema_name:
            sql = f"alter schema {schname} rename to {schname}_new;" \
                f"select count(*) from " \
                f"{schname}_new.{schname}_tbl where i = {value};"
            value += 1
            result = self.commonshpri.executDbSql(sql)
            self.log.info(result)
            self.assertIn(self.constant.alter_schema_success_msg, result)
            self.assertIn('20000', result)

        self.log.info('-----------------------6.删除schema------------------')
        value = 0
        for schname in self.schema_name:
            sql = f"drop schema {schname}_new cascade;"
            value += 1
            result = self.commonshpri.executDbSql(sql)
            self.log.info(result)
            self.assertIn(self.constant.drop_schema_success_msg, result)

    def tearDown(self):
        self.log.info('-----------------------------环境清理--------------------')
        self.log.info("-------------------恢复时间-------------------------")
        current = self.db_standby1_root_node.sh(
            'date "+%m/%d/%Y %H:%M:%S"').result()
        self.log.info(current)

        datecmd = f'date -s "{current}"'
        result = self.db_primary_root_node.sh(datecmd).result()
        self.log.info(datecmd)
        self.log.info(result)

        datecmd = 'hwclock --systohc;service ntpd stop;' \
                  'ntpdate ntp.api.bz;service ntpd start '
        result = self.db_primary_root_node.sh(datecmd).result()
        self.log.info(datecmd)
        self.log.info(result)

        self.log.info('-----------------------删除schema----------------------')
        for schname in self.schema_name:
            sql = f"drop schema if exists {schname} cascade;" \
                f"drop schema if exists {schname}_new cascade;"
            result = self.commonshpri.executDbSql(sql)
            self.log.info(result)
        self.log.info('---Opengauss_Reliability_Dbsys_Case239.py 执行结束-------')